package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BadreplyMapper;
import com.indusfo.spc.mapper.BadreplyTypeMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Badreply;
import com.indusfo.spc.pojo.BadreplyType;
import com.indusfo.spc.service.BadreplyService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class BadreplyServiceImpl implements BadreplyService {

    private  static  final Logger logger = LoggerFactory.getLogger(BadreplyServiceImpl.class);

    @Resource
    private BadreplyMapper badreplyMapper;

    @Resource
    private BadreplyTypeMapper badreplyTypeMapper;

    @Resource
    private UploadMapper uploadMapper;
    /**
     * 不良对策更新
     *
     * @param badreply
     * @return  JSONObject
     */
    @Override
    public JSONObject updateBadreply(Badreply badreply) {
        String remark = badreply.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(badreply.getBadreplyId() == null) {
                throw new ParamsErrorException("请选择要编辑的不良对策");
            }
            checkParam(badreply, remark);
            // 调用存储过程
            int row = badreplyMapper.updateByPrimaryKeySelective(badreply);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 不良对策查询（分页）
     *
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject selectAll(Badreply badreply) {
        List<Badreply> listBadreply = null;
        int count = 0;
        Integer badreplyTypeId = badreply.getBadreplyTypeId();
        List<Integer> badreplyTypeIds = new ArrayList<>();
        try {
            Integer pagesize = badreply.getPagesize();
            Integer pageindex = badreply.getPageindex();
            if(pagesize != null && pageindex != null) {
                badreply.setIncept(pagesize*(pageindex - 1));
            }
            if(badreplyTypeId == null){
                // 如果badreplyTypeId == 0 则查全部
                listBadreply = badreplyMapper.selectAll(badreply);
                //查询分页总记录数
                count = badreplyMapper.countBadreply(badreply); //返回查询到的总记录数
                if (listBadreply.isEmpty()) {
                    return JSONObject.oK("没有不良对策相关数据", listBadreply, count);
                }
                return JSONObject.oK("查询成功", listBadreply, count);
            }
            // 递归查询子类
            recursion(badreplyTypeIds,badreplyTypeId);
            badreplyTypeIds.add(badreplyTypeId);
            // 查询类下所有不良对策
            listBadreply = badreplyMapper.queryBadreplyByBadreplyTypeId(badreply,badreplyTypeIds);
            count = badreplyMapper.countBadreplyByBadreplyTypeId(badreply,badreplyTypeIds);
            return JSONObject.oK("查询成功", listBadreply, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * wangqi
     *
     * 递归查询子类 及其子类的子类
     *
     * 19/9/9   13:22
     * @param badreplyTypeIds
     * @param badreplyTypeId
     */
    private void recursion(List<Integer> badreplyTypeIds, Integer badreplyTypeId) {
        List<Integer> integers = badreplyTypeMapper.queryChild(badreplyTypeId);
        if(integers.size()>0){
        	badreplyTypeIds.addAll(integers);
            for (Integer integer :integers){
                recursion(badreplyTypeIds,integer);
            }
        }
    }

    /***
     * 不良对策新增
     *
     * @param badreply
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject insertBadreply(Badreply badreply) throws ParamsErrorException {
        badreply.setDataState(1);
        String remark = badreply.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(badreply.getBadreplyId() != null) {
                throw new ParamsErrorException("新增不良对策时，不能填写id");
            }
            checkParam(badreply, remark);
            int row = badreplyMapper.insertBadreply(badreply);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 1 启用  2 删除  3停用 不良对策
     *
     * @param badreplyIds
     * @param dataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject deleteBadreply(Long[] badreplyIds, Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (badreplyIds == null) {
                throw new ParamsErrorException("不良对策id不能为空");
            }
            // 执行存储过程
            int row = badreplyMapper.delteBadreply(badreplyIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 参数校验
     *
     * @param badreply
     * @param vcRemark
     */
    private void checkParam(Badreply badreply, String vcRemark) {
        if (badreply.getBadreplyTypeId() == null) {
            throw new ParamsErrorException("不良对策类型不能为空");
        }
        if (StringUtils.isEmpty(badreply.getBadreplyName())) {
            throw new ParamsErrorException("请填写不良对策名称");
        }
        if (badreply.getBadreplyName().getBytes().length > 50) {
            throw new ParamsErrorException("不良对策名超过规定,长度50");
        }
        if (vcRemark.getBytes().length > 100) {
            throw new ParamsErrorException("说明字数超过规定,长度100");
        }
        // 名称不能重复
        Integer depCounts = badreplyMapper.selectBadreply(badreply);
        if (depCounts !=0) {
            throw new ParamsErrorException("该不良对策已存在");
        }
    }

    @Override
    public String checkNoRepeat(Badreply badreply) {
        String badreplyTypeName = badreply.getBadreplyTypeName();
        if(org.apache.commons.lang3.StringUtils.isBlank(badreply.getBadreplyName()) && org.apache.commons.lang3.StringUtils.isBlank(badreplyTypeName)){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if (StringUtils.isEmpty(badreply.getBadreplyName())) {
            return  "不良对策名称为空";
        }
        if (badreply.getBadreplyName().getBytes().length > 50) {
            return  "不良对策名超过规定,长度50";
        }

        if(badreplyTypeName==null){
            return "不良对策类型名称为空";
        }
		
		 Map<String, BadreplyType> badreplyTypeMap =
		 uploadMapper.queryBadCountermeasuresType();
		 if(!badreplyTypeMap.containsKey(badreplyTypeName)){ return "不良对策类型名称填写错误/不规范"; }
		 BadreplyType badreplyType = badreplyTypeMap.get(badreplyTypeName);
		 badreply.setBadreplyTypeId(badreplyType.getBadreplyTypeId());
        if(StringUtils.isEmpty(badreplyTypeName)){}
        // 名称不能重复
        Integer depCounts = badreplyMapper.selectBadreply(badreply);
        if (depCounts !=0) {
            return "该不良对策名称重复";
        }
        return null;
    }

    @Override
    public JSONObject updateListBadreply(List<Badreply> badreplyList) {
		 int flag = uploadMapper.updateListBadreply(badreplyList); if(flag>0){ return
		 JSONObject.oK("新增成功"); }
        return JSONObject.oK("新增失败");
    }

}
